package translateUi
{
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.OutputProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.utils.Timer;
	import flash.utils.setTimeout;
	
	import utils.StringTool;

	/**
	 * 语言转换，中文转 其它 繁体、韩文
	 */
	public class LangTranslateUiMan
	{
		private static var _ins:LangTranslateUiMan;
		public static function get ins():LangTranslateUiMan
		{
			if(!_ins){
				_ins = new LangTranslateUiMan();
			}
			return _ins;
		}
		
		public var mTimer:Timer;
		private var urlArr:Array = [];
		private var curTime:int;
		
		private const LANG_SPLIT:String = "==";
		private const LANG_FILE:String = "lang_ui.txt";
		private const LANG_FILE_CEHUA:String = "lang_ui_cehua.txt";
		private const LANG_FILE_PROGRAM:String = "lang_ui_program.txt";
		private var _langDic:Object = {};
		private var _targetDic:Object = {};
		private var _langLoaded:Boolean = false;
		private var _urlLoader:URLLoader;
		
		private var _timer:Timer;
		private var _cfgStream:FileStream;
		
		/**
		 * 插入文本
		 */
		public function pushLang(txt:String, clsName:String, sortIndex:int = 0):void
		{
			if(_targetDic[txt]){//目标有，也不要重复转换。
				return;
			}
			if(!_langDic[txt]){
				_langDic[txt] = {};
				_langDic[txt]["sort"] = sortIndex;
			}
			if(!_langDic[txt].time){
				var d:Date = new Date();
				var year:int = d.getFullYear();
				var month:int = d.getMonth() + 1;
				var day:int = d.getDate();
				var hours:int = d.getHours();
				var min:int = d.getMinutes();
				var second:int = d.getSeconds();
				_langDic[txt].time = year + "年" + toD(month) + "月" + toD(day) + "日";// + toD(hours) + ":" + toD(min) + ":" + toD(second);
			}
			_langDic[txt]["key"] = txt;
			if(!_langDic[txt].target){
				_langDic[txt].target = "";
			}
			if(!_langDic[txt].clsName){
				_langDic[txt].clsName = [];
			}
			var arr:Array = _langDic[txt].clsName;
			if(arr.indexOf(clsName) == -1){
				arr.push(clsName);
			}
		}
		
		private function toD(num:int):String
		{
			return num < 10 ? "0"+num : ""+num;
		}
		
		private function outputLangTxt():void
		{
			setTimeout(exeOutputLangTxt, 2000);
			setTimeout(exeOutputProgramLangTxt, 1000);
		}
		/**
		 * 导出语言txt
		 */
		private function exeOutputLangTxt():void
		{
			var rootFile:File = new File();
			var path:String = LangTranslateUi.exportUrl;//"C:\Users\Administrator\Desktop\ani-out\flashui"
			path += "\\" + LANG_FILE;
			var fl:File = rootFile.resolvePath(path);
			
			var arr:Array = [];
			for(var key:* in _langDic){
//				_langDic[key]["sort"] = key.length;
				arr.push(_langDic[key]);
			}
			arr.sortOn("sort", Array.NUMERIC);
			var newStr:String = "";
			for(var i:int=0; i<arr.length; i++){
				if(!StringTool.trim(arr[i].target)){//已经有的，策划不想在文本里看到。
					newStr += arr[i].time + LANG_SPLIT + arr[i].key + LANG_SPLIT + (arr[i].target ? arr[i].target : "");
					newStr += "\r\n";
				}
			}
			
			try
			{
				_cfgStream = new FileStream();
//				_cfgStream.addEventListener(Event.COMPLETE, onOutClose);
				_cfgStream.open(fl, FileMode.WRITE);
				_cfgStream.writeUTFBytes(newStr);
				_cfgStream.close();
				
				setTimeout(onOutClose, 3000);
				
//				_timer.addEventListener(TimerEvent.TIMER, onTimer2);
//				_timer.start();
			}
			catch(e:Error)
			{
				throw new Error(e.getStackTrace());
			}
		}
		/**
		 * 给程序自己看的。
		 */
		private function exeOutputProgramLangTxt():void
		{
			var rootFile:File = new File();
			var path:String = LangTranslateUi.exportUrl;//"C:\Users\Administrator\Desktop\ani-out\flashui"
			path += "\\" + LANG_FILE_PROGRAM;
			var fl:File = rootFile.resolvePath(path);
			
			var arr:Array = [];
			for(var key:* in _langDic){
//				_langDic[key]["sort"] = key.length;
				arr.push(_langDic[key]);
			}
			arr.sortOn("sort", Array.NUMERIC);
			var newStr:String = "";
			var clsName:String;
			for(var i:int=0; i<arr.length; i++){
				clsName = JSON.stringify(arr[i].clsName);
				newStr += clsName + LANG_SPLIT + arr[i].key + LANG_SPLIT + (arr[i].target ? arr[i].target : "");
				newStr += "\r\n";
			}
			
			try
			{
				_cfgStream = new FileStream();
				_cfgStream.open(fl, FileMode.WRITE);
				_cfgStream.writeUTFBytes(newStr);
				_cfgStream.close();
			}
			catch(e:Error)
			{
				throw new Error(e.getStackTrace());
			}
		}
		private function onOutClose():void
		{
			_cfgStream.close();
//			_cfgStream.removeEventListener(Event.CLOSE, onOutClose);
			LangTranslateUi.printMsg.text = "LangTranslateMan-全部完成！";
		}
		
		private function loadLangTxt():void
		{
			var rootFile:File = new File();
			var path:String = LangTranslateUi.exportUrl;//"C:\Users\Administrator\Desktop\ani-out\flashui"
			path += "\\" + LANG_FILE_CEHUA;
			var fl:File = rootFile.resolvePath(path);
			if(!fl.exists){
				_langLoaded = true;
				return;
			}
			
			var request:URLRequest = new URLRequest(path);
			_urlLoader = new URLLoader();
			_urlLoader.addEventListener(Event.COMPLETE, onComplete1);
			_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoadError1);
			_urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onLoadError2);
			_urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoadError3);
			_urlLoader.data = null;
			_urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
			_urlLoader.load(request);
		}
		private function onComplete1(e:Event):void
		{
			_urlLoader.removeEventListener(Event.COMPLETE, onComplete1);
			_urlLoader.removeEventListener(IOErrorEvent.IO_ERROR, onLoadError1);
			_urlLoader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, onLoadError2);
			_urlLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoadError3);
			
			var content:String = (_urlLoader.data);
			_langLoaded = true;
			
			var label:TextField = new TextField();
			label.text = content;
			trace("文本行数：" + label.numLines);
			var lines:int = label.numLines;
			var str:String;
			var arr:Array;
			for(var i:int=0; i<lines; i++){
				str = label.getLineText(i);
				str = StringTool.trim(str, ["\r","\n"]);
				if(str && str.indexOf(LANG_SPLIT) != -1){
					arr = str.split(LANG_SPLIT);
					_langDic[arr[1]] = {"time":arr[0], "key":arr[1], "target":(arr[2] ? arr[2] : "")};
					if(arr[2]){
						_targetDic[arr[2]] = true;
					}
				}
			}
			
			_urlLoader.close();
		}
		private function onLoadError1(e:Event):void
		{
			trace("加载是失败");
		}
		private function onLoadError2(e:HTTPStatusEvent):void
		{
			if(e.status >= 400){
				trace("加载是失败2,url="+e.target.url);
			}
		}
		private function onLoadError3(e:Event):void
		{
			trace("安全沙箱错误");
		}
		
		public function LangTranslateUiMan()
		{
			mTimer = new Timer(4);
			
			loadLangTxt();
		}
		public function pushPath(path:String):void
		{
			var index:int = path.lastIndexOf(".ui");
			if(index == path.length - 3){
				urlArr.push(path);
				
				if(!mTimer.running){
					mTimer.addEventListener(TimerEvent.TIMER, onTimerEvent);
					mTimer.start();
				}
			}
		}
		private function onTimerEvent(e:TimerEvent):void
		{
			if(!_langLoaded){
				LangTranslateUi.printMsg.text = "LangTranslateUiMan-正在读取已存在的语言txt。。。";
				return;
			}
			var time:int = new Date().time;
			if(time - curTime < 50){
				if(urlArr.length){
					var str:String = "LangTranslateUiMan-正在加载，还剩余：" + urlArr.length;
					var curUrl:String = urlArr.shift();
					LangTranslateUi.printMsg.text = str + "，\nurl=" + curUrl;
					try{
						new LangTranslateUi().doLoad(curUrl);
					}
					catch(e:*){
						trace("转换出错，路径为：" + curUrl);
					}
				}
				else{
					mTimer.removeEventListener(TimerEvent.TIMER, onTimerEvent);
					mTimer.stop();
					
					LangTranslateUi.printMsg.text = "LangTranslateUiMan-正在导出需要转换的语言txt。。。";
					outputLangTxt();
				}
			}
			curTime = time;
		}
		
	}
}